import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'

import SafeEduDataAnalysis from '../../Compoments/safeEduDataAnalysis'
import { ModuleTitle, Tb } from '../../ModuleTitle'
import { ContentTsx } from '../../contentTsx'
import {
  IDataAnalysisType,
  getStudyInfo,
  getStudyInfoByEntId
} from '../../data'
import type { SwitchAndIntervalRef } from '../../interface'
import { generateCountArray } from '../../utils'

const safeStudyTabs = [
  // { name: "近一年", value: 4 },
  { name: '近一月', value: 4 },
  { name: '近半月', value: 3 },
  { name: '近一周', value: 2 }
]

const SafeStudyModule = forwardRef<SwitchAndIntervalRef, any>((props, ref) => {
  const { selectedAssociationItem, refreshFlag } = useContext(ContentTsx)
  const DataAnalysisCompRef = useRef<{ resize: () => void }>(null)
  const [dataAnalysisType, setDataAnalysisType] = useState<any>(3)
  const [dataAnalysisList, setDataAnalysisList] = useState<any>({
    xvalue: [],
    yvalue: []
  })

  const [maxx, setmaxx] = useState<any>(5)

  const [fresh, refresh] = useState(0)
  const timerRef = useRef<any>(null)

  //今日应学人数
  const [allPer, setAllPer] = useState<number>(0)

  //今日已学
  const [hasStuPer, setHasStuPer] = useState<number>(0)
  const hasStuPerRef = useRef<number>(0)
  const [prevHasStuPer, setPrevHasStuPer] = useState<number>(0)
  const prevHasStuPerRef = useRef<number>(0)
  const [endHasStuPer, setEndHasStuPer] = useState<number>(0)
  const endHasStuPerRef = useRef<number>(0)

  //今日未学
  const [noStuPer, setNoStuPer] = useState<number>(0)
  const noStuPerRef = useRef<number>(0)
  const [prevNoStuPer, setPrevNoStuPer] = useState<number>(0)
  const prevNoStuPerRef = useRef<number>(0)
  const [endNoStuPer, setEndNoStuPer] = useState<number>(0)
  const endNoStuPerRef = useRef<number>(0)

  // timeout
  const hasStuPerTimeoutIdRef = useRef<any>()
  const noStuPerTimeoutIdRef = useRef<any>()

  //数据/时间 分组
  const hasStuPerUpGroupRef = useRef<{
    countGroup: number[]
    timeGroup: number[]
  }>({
    countGroup: [],
    timeGroup: []
  })
  const noStuPerUpGroupRef = useRef<{
    countGroup: number[]
    timeGroup: number[]
  }>({
    countGroup: [],
    timeGroup: []
  })

  const hasStuPerUpGroupIndexRef = useRef<number>(0)
  const noStuPerUpGroupIndexRef = useRef<number>(0)

  function clearCountUp() {
    if (hasStuPerTimeoutIdRef.current) {
      clearTimeout(hasStuPerTimeoutIdRef.current)
    }
    if (noStuPerTimeoutIdRef.current) {
      clearTimeout(noStuPerTimeoutIdRef.current)
    }
  }

  useEffect(() => {
    timerRef.current = setInterval(() => {
      setDataAnalysisType((key: number) => {
        const index = safeStudyTabs.findIndex((v) => v.value === key)
        const next = index === 2 ? 0 : index + 1
        return safeStudyTabs[next].value
      })
    }, 60000)
    return () => {
      clearInterval(timerRef.current)
    }
  }, [fresh])

  //今日应学人数

  const prevAllPer = useMemo(
    () => prevHasStuPer + prevNoStuPer,
    [prevHasStuPer, prevNoStuPer]
  )
  const endAllPer = useMemo(
    () => endHasStuPer + endNoStuPer,
    [endHasStuPer, endNoStuPer]
  )

  //今日已学
  function _recursionHasStuPerSetStartEndCount(gorupIndex: number) {
    if (gorupIndex > hasStuPerUpGroupRef.current.countGroup.length - 1) {
      if (hasStuPerTimeoutIdRef.current) {
        clearTimeout(hasStuPerTimeoutIdRef.current)
      }
      if (endHasStuPerRef.current !== hasStuPerRef.current) {
        console.error(
          `endHasStuPerRef.current 【${endHasStuPerRef.current}】!==hasStuPerRef.current 【${hasStuPerRef.current}】`
        )
      }
      return
    }
    const timeoutTime = Math.max(
      1,
      hasStuPerUpGroupRef.current.timeGroup[gorupIndex] - 1
    )
    if (hasStuPerTimeoutIdRef.current) {
      clearTimeout(hasStuPerTimeoutIdRef.current)
    }
    hasStuPerTimeoutIdRef.current = setTimeout(() => {
      if (gorupIndex === 0) {
        //初始化时是从1开始的，以后每次更新是从0开始的
        prevHasStuPerRef.current = endHasStuPerRef.current
      } else if (gorupIndex > 0) {
        prevHasStuPerRef.current +=
          hasStuPerUpGroupRef.current.countGroup[gorupIndex - 1]
      }
      setPrevHasStuPer(prevHasStuPerRef.current)

      const currEndCount =
        hasStuPerUpGroupRef.current.countGroup[gorupIndex] +
        prevHasStuPerRef.current
      endHasStuPerRef.current = currEndCount
      setEndHasStuPer(currEndCount)
    }, timeoutTime * 1000)
  }
  const handleHasStuCountUpEnd = () => {
    //初始化CountUp.start === 0 && CountUp.end === 0 时也会在duration 1s之后执行onEnd回调函数
    hasStuPerUpGroupIndexRef.current += 1
    _recursionHasStuPerSetStartEndCount(hasStuPerUpGroupIndexRef.current)
  }

  //今日未学
  function _recursionNoStuPerSetStartEndCount(gorupIndex: number) {
    if (gorupIndex > noStuPerUpGroupRef.current.countGroup.length - 1) {
      if (noStuPerTimeoutIdRef.current) {
        clearTimeout(noStuPerTimeoutIdRef.current)
      }
      if (endNoStuPerRef.current !== noStuPerRef.current) {
        console.error(
          `endNoStuPerRef.current 【${endNoStuPerRef.current}】!==noStuPerRef.current 【${noStuPerRef.current}】`
        )
      }
      return
    }
    const timeoutTime = Math.max(
      1,
      noStuPerUpGroupRef.current.timeGroup[gorupIndex] - 1
    )
    if (noStuPerTimeoutIdRef.current) {
      clearTimeout(noStuPerTimeoutIdRef.current)
    }
    noStuPerTimeoutIdRef.current = setTimeout(() => {
      if (gorupIndex === 0) {
        //初始化时是从1开始的，以后每次更新是从0开始的
        prevNoStuPerRef.current = endNoStuPerRef.current
      } else if (gorupIndex > 0) {
        prevNoStuPerRef.current +=
          noStuPerUpGroupRef.current.countGroup[gorupIndex - 1]
      }
      setPrevNoStuPer(prevNoStuPerRef.current)

      const currEndCount =
        noStuPerUpGroupRef.current.countGroup[gorupIndex] +
        prevNoStuPerRef.current
      endNoStuPerRef.current = currEndCount
      setEndNoStuPer(currEndCount)
    }, timeoutTime * 1000)
  }
  const handleNoStuCountUpEnd = () => {
    noStuPerUpGroupIndexRef.current += 1
    _recursionNoStuPerSetStartEndCount(noStuPerUpGroupIndexRef.current)
  }

  //初始化/切换协会时 获取数据
  function _initialOrSwitchAssociation(
    type: 'inital' | 'switchAssociation',
    associationKey: string
  ) {
    if (type === 'switchAssociation') {
      clearCountUp()
      //今日应学人数
      setAllPer(0)

      //今日已学
      setHasStuPer(0)
      hasStuPerRef.current = 0
      setPrevHasStuPer(0)
      prevHasStuPerRef.current = 0
      setEndHasStuPer(0)
      endHasStuPerRef.current = 0

      //今日未学
      setNoStuPer(0)
      noStuPerRef.current = 0
      setPrevNoStuPer(0)
      prevNoStuPerRef.current = 0
      setEndNoStuPer(0)
      endNoStuPerRef.current = 0

      //数据/时间 分组
      hasStuPerUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      noStuPerUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }

      hasStuPerUpGroupIndexRef.current = 0
      noStuPerUpGroupIndexRef.current = 0
    }

    getStudyInfo({ entId: associationKey })
      .then((res) => {
        const {
          allPersonNum = 0,
          studyPersonNum = 0,
          noStudyPersonNum = 0
        } = res.data ?? {}
        setAllPer(allPersonNum)
        setHasStuPer(studyPersonNum)
        hasStuPerRef.current = studyPersonNum
        setNoStuPer(noStudyPersonNum)
        noStuPerRef.current = noStudyPersonNum

        if (studyPersonNum > 0) {
          endHasStuPerRef.current = studyPersonNum
          setEndHasStuPer(studyPersonNum)
        }

        if (noStudyPersonNum > 0) {
          endNoStuPerRef.current = noStudyPersonNum
          setEndNoStuPer(noStudyPersonNum)
        }
      })
      .catch((err) => {
        console.error(
          '--SafeStudyModule--_initialOrSwitchAssociation--getStudyInfo--err--:',
          err
        )
      })
  }

  //5分钟刷新时
  function _intervalRefresh() {
    clearCountUp()
    getStudyInfo({ entId: selectedAssociationItem.key })
      .then((res) => {
        const {
          allPersonNum = 0,
          studyPersonNum = 0,
          noStudyPersonNum = 0
        } = res.data ?? {}
        setAllPer(allPersonNum)
        setHasStuPer(studyPersonNum)
        hasStuPerRef.current = studyPersonNum
        setNoStuPer(noStudyPersonNum)
        noStuPerRef.current = noStudyPersonNum

        //今日已学
        const hasStuPerDiff = studyPersonNum - endHasStuPerRef.current
        if (hasStuPerDiff === 0) {
          return
        } else {
          hasStuPerUpGroupIndexRef.current = 0
          hasStuPerUpGroupRef.current = generateCountArray(
            endHasStuPerRef.current,
            studyPersonNum
          )
          if (hasStuPerDiff < 0) {
            hasStuPerUpGroupRef.current = {
              countGroup: hasStuPerUpGroupRef.current.countGroup.map(
                (count) => count * -1
              ),
              timeGroup: hasStuPerUpGroupRef.current.timeGroup
            }
          }
          _recursionHasStuPerSetStartEndCount(hasStuPerUpGroupIndexRef.current)
        }

        //今日未学
        const noStuPerDiff = noStudyPersonNum - endNoStuPerRef.current
        if (noStuPerDiff === 0) {
          return
        } else {
          noStuPerUpGroupIndexRef.current = 0
          noStuPerUpGroupRef.current = generateCountArray(
            endNoStuPerRef.current,
            noStudyPersonNum
          )
          if (noStuPerDiff < 0) {
            noStuPerUpGroupRef.current = {
              countGroup: noStuPerUpGroupRef.current.countGroup.map(
                (count) => count * -1
              ),
              timeGroup: noStuPerUpGroupRef.current.timeGroup
            }
          }
          _recursionNoStuPerSetStartEndCount(noStuPerUpGroupIndexRef.current)
        }
      })
      .catch((err) => {
        console.error(
          '--SafeStudyModule--_intervalRefresh--getStudyInfo--err--:',
          err
        )
      })
  }

  useImperativeHandle(ref, () => ({
    switchAssociation: (newAssociationId) => {
      _initialOrSwitchAssociation('switchAssociation', newAssociationId)
    },
    intervalRefresh: _intervalRefresh,
    resize: () => {
      if (DataAnalysisCompRef.current) {
        DataAnalysisCompRef.current.resize()
      }
    }
  }))

  useEffect(() => {
    _initialOrSwitchAssociation('inital', selectedAssociationItem.key)
    return () => {
      clearCountUp()
    }
  }, [])

  //新增数据分析切换 MouseEnter
  const handleTitleTabMouseEnter: React.MouseEventHandler = (event) => {
    clearInterval(timerRef.current)
  }

  //新增数据分析切换 MouseLeave
  const handleTitleTabMouseLeave: React.MouseEventHandler = (event) => {
    refresh(Math.random())
  }
  //----数据接口----
  function _getDataAnalysis(dataAnalysisTypeParam: any) {
    clearInterval(timerRef.current)
    getStudyInfoByEntId({
      entId: selectedAssociationItem.key,
      type: dataAnalysisTypeParam == 4 ? 3 : dataAnalysisTypeParam
    })
      .then((res) => {
        const { data = [] } = res
        if (dataAnalysisTypeParam == 2) {
          //处理周方法
          const wformattedDates = data.map((item) => {
            const dateParts = item.date.split('-')
            return dateParts[2].replace(/^0+/, '') + '日'
          })
          const wformattedDatesvalue = data.map((item) => {
            return item.studyPersonNum
          })
          const x =
            Math.max.apply(
              null,
              wformattedDatesvalue.map((el: any) => el)
            ) < 5
              ? 5
              : Math.max.apply(
                  null,
                  wformattedDatesvalue.map((el: any) => el)
                )
          setmaxx(x)
          const paparm = {
            xvalue: wformattedDates,
            yvalue: wformattedDatesvalue
          }
          setDataAnalysisList(paparm)
        } else if (dataAnalysisTypeParam == 3) {
          //处理月方法
          const mformattedDates = data.map((item) => {
            const dateParts = item.date.split('-')
            return dateParts[2].replace(/^0+/, '') + '日'
          })
          const wformattedDatesvalue = data.map((item) => {
            return item.studyPersonNum
          })
          const x =
            Math.max.apply(
              null,
              wformattedDatesvalue.slice(15, 30).map((el: any) => el)
            ) < 5
              ? 5
              : Math.max.apply(
                  null,
                  wformattedDatesvalue.slice(15, 30).map((el: any) => el)
                )
          setmaxx(x)
          const paparm = {
            xvalue: mformattedDates.slice(15, 30),
            yvalue: wformattedDatesvalue.slice(15, 30)
          }
          setDataAnalysisList(paparm)
        } else if (dataAnalysisTypeParam == 4) {
          const mformattedDates = data.map((item) => {
            const dateParts = item.date.split('-')
            return dateParts[2].replace(/^0+/, '') + '日'
          })
          const wformattedDatesvalue = data.map((item) => {
            return item.studyPersonNum
          })
          const x =
            Math.max.apply(
              null,
              wformattedDatesvalue.map((el: any) => el)
            ) < 5
              ? 5
              : Math.max.apply(
                  null,
                  wformattedDatesvalue.map((el: any) => el)
                )
          setmaxx(x)
          const paparm = {
            xvalue: mformattedDates,
            yvalue: wformattedDatesvalue
          }
          setDataAnalysisList(paparm)
        }
        //年的先注释
        //  else if (dataAnalysisTypeParam == 4) {
        //   const yformattedDates = data.map((item) => {
        //     const dateParts = item.date.split("-")
        //     return dateParts[1].replace(/^0+/, "") + "月"
        //   })

        //   const wformattedDatesvalue = data.map((item) => {
        //     return item.studyPersonNum
        //   })
        //   const x =
        //     Math.max.apply(
        //       null,
        //       wformattedDatesvalue.map((el: any) => el)
        //     ) < 5
        //       ? 5
        //       : Math.max.apply(
        //           null,
        //           wformattedDatesvalue.map((el: any) => el)
        //         )
        //   setmaxx(x)
        //   const paparm = {
        //     xvalue: yformattedDates,
        //     yvalue: wformattedDatesvalue
        //   }
        //   setDataAnalysisList(paparm)
        // }
        refresh(Math.random())
      })
      .catch((err) => {
        console.error('--BigScreenBase--getDataAnalysis--err--:', err)
      })
  }
  useEffect(() => {
    _getDataAnalysis(dataAnalysisType)
  }, [selectedAssociationItem.key, dataAnalysisType])
  //数据切换
  const handleDataAnalysisTabChange = (activeTab: Tb) => {
    refresh(Math.random())
    if (activeTab.value === dataAnalysisType) return
    const currType = activeTab.value as IDataAnalysisType
    setDataAnalysisType(currType)
  }
  return (
    <div
      className="bigscreen-module ms-module "
      style={{ height: 373, overflow: 'hidden' }}
    >
      <ModuleTitle title={'安全教育'}></ModuleTitle>
      <div style={{ padding: '14px 23px 0px 23px' }}>
        <div
          className="drvierCount flexr jub"
          style={{ minHeight: 53, maxHeight: 71, overflow: 'hidden' }}
        >
          <div style={{ width: '85px' }}>
            <div className="dr_count_num">
              <CountUp start={prevAllPer} end={endAllPer} duration={1} />
            </div>
            <div className="dr_label">今日应学人数</div>
          </div>
          <div style={{ width: '85px' }}>
            <div className="dr_count_num">
              <CountUp
                start={prevHasStuPer}
                end={endHasStuPer}
                duration={1}
                onEnd={handleHasStuCountUpEnd}
              />
            </div>
            <div className="dr_label">今日已学</div>
          </div>
          <div style={{ width: '85px' }}>
            <div className="dr_count_num">
              <CountUp
                start={prevNoStuPer}
                end={endNoStuPer}
                duration={1}
                onEnd={handleNoStuCountUpEnd}
              />
            </div>
            <div className="dr_label">今日未学</div>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 18 }}>
        <div className="bigscreen-content">
          <LineP></LineP>
          <ModuleTitle
            onTitleTabMouseEnter={handleTitleTabMouseEnter}
            onTitleTabMouseLeave={handleTitleTabMouseLeave}
            title={'数据统计'}
            className="Mt_nobg"
            diplonema={false}
            titleTxtStyle={{ padding: 0 }}
            titleBgStyle={{
              backGround: 'none',
              backgroundImage: 'none',
              border: 'none'
            }}
            activeKey={dataAnalysisType}
            tab={safeStudyTabs}
            tabChange={handleDataAnalysisTabChange}
          ></ModuleTitle>
          <SafeEduDataAnalysis
            maxx={maxx}
            dataAnalysisList={dataAnalysisList}
            ref={DataAnalysisCompRef}
          />
        </div>
      </div>
    </div>
  )
})

export default SafeStudyModule

function LineP() {
  return (
    <div className="line-radius">
      <div className="line-pieicon"></div>
    </div>
  )
}
